package com.shundr.shipper.frame.service;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import cn.jpush.android.api.JPushInterface;

import com.shundr.shipper.cargo.dao.CargoDao;
import com.shundr.shipper.cargo.model.CargoInfo;
import com.shundr.shipper.common.CommonWebViewActivity;
import com.shundr.shipper.common.SystemSmsActivity;
import com.shundr.shipper.common.model.SystemMessageInfo;
import com.shundr.shipper.common.util.DateUtil;
import com.shundr.shipper.common.util.JsonUtil;
import com.shundr.shipper.common.util.NetworkUtil;
import com.shundr.shipper.common.util.NotificationUtils;
import com.shundr.shipper.common.util.PrefConstants;
import com.shundr.shipper.common.util.PrefUtils;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.util.LLogger;
import com.shundr.shipper.frame.util.StringUtil;

/**
 * 
 * PushMessageReceiver 极光推送接收器
 * 
 * @author larry 2015-4-11 下午2:17:43 
 * @version 1.0.0
 *
 */
public class PushMessageReceiver extends BroadcastReceiver {
	private static final String TAG = "JPush";
	public static final String ACTION_CHECK_NETWORK = "com.shundr.action.CHECK_NETWORK";
	private static final String MESSAGE_TYPE = "shundr_sys_message";
	public static ArrayList<ReceiverHandler> mReceiverListeners = new ArrayList<ReceiverHandler>();
	public static ArrayList<EventHandler> mListeners = new ArrayList<EventHandler>();
	private CargoDao mCargoDao;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			LLogger.e(TAG, "[MyReceiver] 接收Registration Id : " + regId);
			// send the Registration Id to your server...
		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
				.getAction())) {
//			LLogger.e(TAG,"[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
			try {
				String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
				JSONObject object = new JSONObject(message);
				if(!object.has(MESSAGE_TYPE)){//常跑路线货源
					if (LContext.isLogin()) {
//						displayRouteCargo(context, bundle);
					}
				}else{
					//系统消息
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
				.getAction())) {
			LLogger.e(TAG, "[MyReceiver] 接收到推送下来的通知");
			receivingNotification(context, bundle);
		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
				.getAction())) {
			LLogger.e(TAG, "[MyReceiver] 用户点击打开了通知");
			openNotification(context, bundle);
		} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
			LLogger.e(TAG,"[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
			// 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
			// 打开一个网页等..
		} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
			boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
			LLogger.e(TAG, "[MyReceiver]" + intent.getAction()+ " connected state change to " + connected);
		} else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
			LLogger.e("网络变化");
//			Toast.makeText(context, "网络变化", Toast.LENGTH_SHORT).show();
			NetworkUtil.checkNetworkStatus(context);
			if (mListeners.size() > 0)// 通知接口完成加载
				for (EventHandler handler : mListeners) {
					handler.onNetChange();
				}
		} else if (ACTION_CHECK_NETWORK.equals(intent.getAction())) {
			LLogger.e("主动检测网络变化");
//			Toast.makeText(context, "网络变化", Toast.LENGTH_SHORT).show();
			NetworkUtil.checkNetworkStatus(context);
			if (mListeners.size() > 0)// 通知接口完成加载
				for (EventHandler handler : mListeners) {
					handler.onNetChange();
				}
		} else {
			LLogger.e(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
		}
	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}

	/**
	 * @param context
	 * @param bundle
	 */
	private void displayRouteCargo(Context context, Bundle bundle) {
		if(mCargoDao == null){
			mCargoDao = new CargoDao();
		}
		 String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
		 JSONObject object = null;
		 try {
			object = new JSONObject(message);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		 // 如果界面在前端，就通过广播发送到前端，否则保存在ReceivedCargoManager 对象中
		 CargoInfo cargoInfo= JsonUtil.fromJson(object.toString(), CargoInfo.class);
		 if (cargoInfo == null
					|| StringUtil.isNull(cargoInfo.getCargoSrcCode() + "")
					|| StringUtil.isNull(cargoInfo.getCargoDstCode() + "")) {
				LLogger.e(TAG, "the received cargoinfo is null");
				return;
			}
		cargoInfo.setLocalType(CargoInfo.CargoLocalType.unread);
		cargoInfo.setLocalUserId(LContext.USER_ID);
		cargoInfo.setCargoInsertTime(DateUtil.getNowTime());
		mCargoDao.insert(cargoInfo);
		LLogger.e(TAG, "the received cargoinfo has insert");
		LContext.isTtsOpened = PrefUtils.getPrefBoolean(context, PrefConstants.IS_TTS_ON, true);
		if(LContext.isTtsOpened){
			String speakStr = "有新货，从" + cargoInfo.getCargoSrcPlace() + "到" + cargoInfo.getCargoDstPlace(); 
			if(LContext.isBackground(context)){
				NotificationUtils.notifys(context, "常跑路线货源", "从" + cargoInfo.getCargoSrcPlace() + "到" + cargoInfo.getCargoDstPlace());
			}
			LContext.getTtsTools(context).speak(speakStr);	
		}
		
		for (ReceiverHandler handler : mReceiverListeners) {
			handler.onReceived(MessageConfig.CARGO);
		}
	}
	
	private void receivingNotification(Context context, Bundle bundle){
        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
        LLogger.d(TAG, " title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        LLogger.d(TAG, "message : " + message);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        LLogger.d(TAG, "extras : " + extras);
    } 
 
   private void openNotification(Context context, Bundle bundle){
        String message = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String myValue = "";
        try {
        	JSONObject object = new JSONObject(message);
        	if(object.has(MESSAGE_TYPE)){//系统消息
        		myValue = object.optString(MESSAGE_TYPE);
        		SystemMessageInfo info = JsonUtil.fromJson(myValue, SystemMessageInfo.class);
        		switch (info.getType()) {
				case 0://货源
					Intent cargo = new Intent(context, SystemSmsActivity.class);
					cargo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        		context.startActivity(cargo);
					break;
				case 1://活动
					Intent act = new Intent(context, CommonWebViewActivity.class);
					act.putExtra("url", info.getUrl());
					act.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        		context.startActivity(act);
					break;

				default:
					break;
				}
        	}
        } catch (Exception e) {
            LLogger.e(TAG, "Unexpected: extras is not a valid json" + e);
            return;
        }
    }
	
	public static abstract interface ReceiverHandler {
		public abstract void onReceived(int type);
	}
	public static abstract interface EventHandler {
		public abstract void onNetChange();
	}
}
